package calao.plan;

import calao.plan.client.Task;
import calao.storage.DataBinding;
import calao.storage.DataReader;
import calao.storage.DataWriter;
import calao.storage.SchemaElement;
import calao.storage.UnknownBindingException;

public abstract class TaskType<T extends Task> 
extends SchemaElement
{
	
	public final TypeDataBinding<T> binding;
	
	public TaskType(Class<T> jtype, String name) 
	{
		super(name);
		this.binding = new TypeDataBinding<T>(this, jtype, name);
	}
	
	abstract public void writeTypeData(DataWriter writer, T task);

	abstract public void readTypeData(DataReader reader, T task)
	throws UnknownBindingException;
	
	@Override
	public Iterable<SchemaElement> getChildElements()
	{
		return java.util.Arrays.asList((SchemaElement)binding);
	}
	
	public static TaskType getTaskType(Task task)
	{
		DataBinding binding = DataBinding.getBinding(task.getClass());
		if (binding!=null && binding instanceof TypeDataBinding) {
			return ((TypeDataBinding)binding).type;
		}
		return null;
	}
	
	public T[] newTaskArray(int length)
	{
		return calao.util.Arrays.newArray(binding.getDataType(), length);
	}
	
	@SuppressWarnings("unchecked")
	public T downcast(Task task)
	{
		return task.getClass()==binding.getDataType()? (T)task : null;
	}
	
	@Override
	protected void register() { }
	
}
